package com.turing.post.datatranfer.impl;

import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.cardmanagement.util.CardStockDao;
import com.turing.post.cardmanagement.util.IssueCardStockDetailDao;
import com.turing.post.datatranfer.util.ActivateCardBusiness;
import com.turing.post.datatranfer.util.CardTradDetailBusiness;
import com.turing.post.datatranfer.util.EntityCardDao;
import com.turing.post.datatranferpibs.util.CardManager;
import com.turing.post.datatranferpibs.util.CardManagerDetail;
import com.turing.post.datatranferpibs.util.TradHistoryDetailDao;
import com.turing.post.thirdinterface.util.MapCardClassicDao;
import com.turing.post.thirdinterface.util.MapIssueBranchDao;
import com.turing.post.thirdinterface.util.MapMchTradDetail;
import com.turing.post.thirdinterface.util.MapMchTradDetailDao;
import com.turing.post.thirdinterface.util.MapSaleBranchDao;
import com.turing.post.transaction.util.MchHisTradDetail;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.SHA1;

/**
 * @author zxp
 * @Jan 28, 2013
 */
@Stateless(mappedName = "datatranfer.impl.CardTradDetailBusinessImpl")
@Remote
@Local
public class CardTradDetailBusinessImpl implements CardTradDetailBusiness {

	@EJB(mappedName = "datatranfer.impl.CardTradDetailBusinessImpl")
	private CardTradDetailBusiness cardTradDetailBusinessImpl;

	// @EJB(mappedName = "datatranfer.impl.CardTradDetailDaoImpl")
	// private CardTradDetailDao cardTradDaoImpl;

	// @EJB(mappedName = "account.impl.AccountSystemHisTradDetailDaoImpl")
	// private AccountSystemHisTradDetailDao accHisTradDaoImpl;
	//
	// @EJB(mappedName = "account.impl.AccountSystemAddTradDetailDaoImpl")
	// private AccountSystemAddTradDetailDao accAddTradDaoImpl;
	//
	// @EJB(mappedName = "account.impl.MasterAccountDaoImpl")
	// private MasterAccountDao masterAccountDaoImpl;
	//
	// @EJB(mappedName = "account.impl.SubAccountDaoImpl")
	// private SubAccountDao subAccountDaoImpl;

	// /**
	// * a) 从已迁移卡交易流水列表中取最大的流水,再从老系统找比这个最大流水号大的最小的流水号.如果没找到,迁移结束.
	// * b)根据得到的流水号从旧数据库中查出卡交易流水集合. c) 在新系统AccountSystemHisTradDetail表中插入一条记录.
	// * d)在新系统AccountSystemAddTradDetail表中逐条插入 b步骤得到的流水集合.
	// * e)将本事务使用的旧系统流水号记录到已迁移卡交易流水中. f) 转A执行下一条流水.
	// */
	// // 数据转移
	// @Override
	// public Integer tranferCardTradDetail(Integer page, Integer num)
	// throws PCPSApplicationException {
	// long start = System.currentTimeMillis();
	// // 待迁移一页数据
	// CardTradDetail ctd = null;
	// String mapTranseqno = null;
	// // 分页数据
	// List<CardTradDetail> pageList = cardTradDaoImpl.getCardTradDetailList(
	// page, num);
	// for (int i = 0; i < pageList.size(); i++) {
	// ctd = pageList.get(i);
	// // 改密,延期数据不迁移
	// if (ctd.getTrancode().equals(90) || ctd.getTrancode().equals(99)) {
	// continue;
	// }
	// mapTranseqno = mapDaoImpl.getTranseqno(ctd.getTranseqno());
	// if (!PCPSUtil.isEmpty(mapTranseqno)) {
	// // 该条流水已经迁移
	// continue;
	// }
	// // 判断主账号，子账号是否存在
	// MasterAccount ma = masterAccountDaoImpl
	// .getMasterAccountByMasterAccNo(new BigInteger("113"));
	// // MasterAccount ma = masterAccountDaoImpl
	// // .getMasterAccountByCardNo(ctd.getCardno());
	// if (ma == null) {
	// continue;
	// // PCPSUtil.Log("TranferCardTradDetail失败：" + ctd.getCardno()
	// // + "未找到主账号!");
	// // break;
	// }
	// List<SubAccount> saList = subAccountDaoImpl
	// .getSubAccountListByMasterAccNo(ma.getMasterAccNo());
	// if (saList == null || saList.size() < 1) {
	// continue;
	// // PCPSUtil.Log("TranferCardTradDetail失败：" + ctd.getCardno()
	// // + "未找到子账号!");
	// // break;
	// }
	// // 数据迁移
	// tranferData(ctd, ma, saList.get(0));
	// }
	// PCPSUtil.Log("TranferCardTradDetail迁移第" + page + "页耗时："
	// + (System.currentTimeMillis() - start) / 1000 + "秒");
	// return pageList.size();
	// }
	//
	// /**
	// * 设置独立事务，进入打开事务，失败关闭事务
	// *
	// * @param ctd
	// * @param ma
	// * @param subAccount
	// * @throws PCPSApplicationException
	// */
	// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	// private void tranferData(CardTradDetail ctd, MasterAccount ma,
	// SubAccount subAccount) throws PCPSApplicationException {
	//
	// CardTradDetail waitctd = null;
	// List<CardTradDetail> waitList = null;
	// AccountSystemHisTradDetail ashtd = null;
	// AccountSystemAddTradDetail asatd = null;
	// MapCardTradDetail mctd = null;
	//
	// // 需要迁移的数据列表
	// waitList = cardTradDaoImpl.getCardTradDetailList(ctd.getTranseqno());
	// if (waitList.size() > 1) {
	// // 合计
	// BigInteger sunAmount = BigInteger.ZERO;
	// // 多条记录时处理
	// for (int j = 0; j < waitList.size(); j++) {
	// waitctd = waitList.get(j);
	// sunAmount = sunAmount.add(waitctd.getAmount());
	// // 插入AccountSystemAddTradDetail,单条记录顺序号为1
	// asatd = createAccountSystemAddTradDetail(waitctd, j + 1, ma,
	// subAccount);
	// accAddTradDaoImpl.insert(asatd);
	// }
	// // 插入AccountSystemHisTradDetail
	// ashtd = createAccountSystemHisTradDetail(ctd, sunAmount);
	// accHisTradDaoImpl.insert(ashtd);
	// // 插入MapCardTradDetail
	// mctd = new MapCardTradDetail();
	// mctd.setTranseqno(ctd.getTranseqno());
	// mapDaoImpl.insertMapCardTradDetail(mctd);
	// } else if (waitList.size() == 1) {
	// // 插入AccountSystemHisTradDetail
	// ashtd = createAccountSystemHisTradDetail(ctd, ctd.getAmount());
	// accHisTradDaoImpl.insert(ashtd);
	// // 插入AccountSystemAddTradDetail,单条记录顺序号为1
	// asatd = createAccountSystemAddTradDetail(ctd, 1, ma, subAccount);
	// accAddTradDaoImpl.insert(asatd);
	// // 插入MapCardTradDetail
	// mctd = new MapCardTradDetail();
	// mctd.setTranseqno(ctd.getTranseqno());
	// mapDaoImpl.insertMapCardTradDetail(mctd);
	// } else {
	// PCPSUtil.Log("TranferCardTradDetail迁移需要迁移的数据列表未找到："
	// + ctd.getTranseqno());
	// }
	// }
	//
	// private AccountSystemAddTradDetail createAccountSystemAddTradDetail(
	// CardTradDetail ctd, Integer accsubseqno, MasterAccount ma,
	// SubAccount subAccount) {
	// AccountSystemAddTradDetail asatd = new AccountSystemAddTradDetail();
	// asatd.setAccSeqNo(ctd.getTranseqno());// 帐户子系统流水号 varchar(40) Not Null
	// asatd.setAccSubSeqNo(accsubseqno);// 记帐子序号 Int Not Null
	// asatd.setIssueCompanyNo(TranferConfig.ICCNO);// 发卡商NO
	// if (ctd.getChanneltrandate() == null) {
	// asatd.setTranDate(PCPSUtil.getShortDateFromLongDate(ctd
	// .getTradtime()));
	// } else {
	// asatd.setTranDate(ctd.getChanneltrandate());// TranDate 帐务日期
	// }
	// asatd.setTranTime(ctd.getTradtime());// 记帐时间
	// asatd.setMasterAccNo(ma.getMasterAccNo());// 主帐号 int Not Null
	// asatd.setCardNo(ctd.getCardno());// 卡号 char(19) Null
	// // asatd.setCardClassId 卡种类ID int Null
	// asatd.setSubAccNo(subAccount.getSubAccNo());// 子帐号 Int Not Null
	// asatd.setOpenBranchNo(subAccount.getOpenBranchNo());// 开户机构号 varchar(26)
	// asatd.setTranType(getTrancede(ctd.getTrancode()));// 记账类型
	// asatd.setDebitAmount(ctd.getAmount());// 借方发生额
	// asatd.setCreditAmount(BigInteger.ZERO); // 贷方发生额
	// asatd.setBalance(ctd.getBalance()); // 交易后余额 decimal(16) Not Null >=0
	// asatd.setMasBalance(ma.getBalance());// 主帐户余额
	// asatd.setRemark(ctd.getChannelabstract());
	// return asatd;
	// }
	//
	// private AccountSystemHisTradDetail createAccountSystemHisTradDetail(
	// CardTradDetail ctd, BigInteger amount) {
	// // CardTradDetail
	// // batchno;// char(6) n 无对应不迁移
	// // cardno; // char(16) n ++++++++++++++++
	// // transeqno; // char(22) n ++++++++++++++++
	// // trancode;// ;char(2) n +++++++++++++++
	// // tradtime;// date n ++++++++++++++++
	// // channelid;// char(2) n 无对应不迁移
	// // amount;// number(8) n 0 ++++++++++++++++
	// // balance;// number(8) n ++++++++++++++++
	// // canceltranseqno;// ++++++++++++
	// // channelseqno;// varchar2(20) y ++++++++++++++
	// // channeltrandate;// date y ++++++++++++++
	// // channelabstract;// varchar2(20) y ++++++++++++++
	// AccountSystemHisTradDetail ashtd = new AccountSystemHisTradDetail();
	// ashtd.setAccSeqNo(ctd.getTranseqno());// AccSeqNo 帐户子系统流水号
	// if (ctd.getChanneltrandate() == null) {
	// ashtd.setTranDate(PCPSUtil.getShortDateFromLongDate(ctd
	// .getTradtime()));
	// } else {
	// ashtd.setTranDate(ctd.getChanneltrandate());// TranDate 帐务日期
	// }
	// ashtd.setIssueCompanyNo(TranferConfig.ICCNO);// IssueCompanyNo(FK)
	// ashtd.setTranTime(ctd.getTradtime());// TranTime 交易时间
	// if (PCPSUtil.isEmpty(ctd.getChannelseqno())) {
	// // 自动产生
	// ashtd.setTranSeqNo(TranferConfig.ICCNO
	// + PCPSUtil.getStringYMDHMSPackedByDate(ctd.getTradtime()));// 交易子系统流水号
	// } else {
	// ashtd.setTranSeqNo(ctd.getChannelseqno());// TranSeqNo 交易子系统流水号
	// }
	// ashtd.setDebitAmount(amount);// 合计借方发生额 decimal(16) Not Null
	// // 可正可负,消费/消费取消/扣费/扣费取消/销户/销户取消
	// ashtd.setCreditAmount(BigInteger.ZERO);// 合计贷方发生额
	// ashtd.setCancelAccSeqNo(ctd.getCanceltranseqno());// 撤销/被撤销帐户子系统流水号
	// ashtd.setCancelTranDate(ctd.getChanneltrandate());// 撤销/被撤销帐务日期 date
	// // ashtd.setCancelTranSeqNo();//撤销/被撤销交易子系统流水号
	// // ashtd.setOperId(); 操作员ID int Null
	// ashtd.setSummary("迁移数据");// 交易摘要 varchar(60) Null
	// return ashtd;
	// }

	// private String getTrancede(String trancede) {
	// if ("80".equals(trancede)) {
	// // 消费
	// return "01";
	// }
	// if ("81".equals(trancede)) {
	// // 取消
	// return "11";
	// }
	// if ("82".equals(trancede)) {
	// // 自动冲正
	// return "11";
	// }
	// return null;
	// }

	// @Override
	// public BigInteger getCardTradDetailTotal() {
	// return cardTradDaoImpl.getCardTradDetailTotal();
	// }

	/**
	 * 日终后 便民驿站 表数据======================================
	 */
	@Override
	public void tranferPIBSDataByTranDate(String brNo, String ip, Integer port,
			String tranDate, String merchantNo, String faceMrchBrchNo,
			String webMrchBrchNo) throws PCPSApplicationException {
		String webBranchNo = "6101041030";// 网站缴费机构号
		String branchNo = "";
		String pwd = "00000000";
		// 交易流水 按日期查询
		List<CardManager> cmList = tradHistoryDetailDaoImpl
				.getCardManagerListByTranDate(brNo, tranDate);
		if (cmList == null || cmList.size() < 1) {
			return;
		}
		System.out.println("流水笔数：" + cmList.size());
		String[] strS = null;
		// int i=0;
		for (CardManager cm : cmList) {
			// 判断是否撤销
			strS = tradHistoryDetailDaoImpl
					.getTradHistoryDetailByCardManager(cm);
			// i++;
			// if("6101041023".equals(cm.getBranchNo())){
			// System.out.println("第"+i+"行"+cm.getBranchNo()+"|"+cm.getTranSeqNo()+"|"+strS[3]);
			// }
			if (strS != null) {
				// 撤销交易流水号
				if (PCPSUtil.isEmpty(strS[0])) {
					// delegaterespcode==0
					if ("0".equals(strS[1].trim())) {
						// 非撤销交易数据
						// strS[2] 交易码 转换？？？？？？1 1001 1800 1101 1806
						if (webBranchNo.equals(cm.getBranchNo())) {
							// 新系统网站商户分支机构号
							branchNo = webMrchBrchNo;
						} else {
							// 新系统实体店商户分支机构号
							branchNo = faceMrchBrchNo;

						}
						// if("6101041023".equals(cm.getBranchNo())){
						// System.out.println("第"+i+"========行"+cm.getBranchNo()+"|"+cm.getTranSeqNo()+"|"+strS[3]);
						// }
						cardTradDetailBusinessImpl.pmbsData(cm, strS,
								merchantNo, branchNo, pwd, ip, port);
					}
				}
			}
		}
	}

	@EJB(mappedName = "thirdinterface.impl.MapMchTradDetailDaoImpl")
	private MapMchTradDetailDao mapMchTradDetailDaoImpl;

	@Override
	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public void pmbsData(CardManager cm, String[] strS, String merchantNo,
			String branchNo, String pwd, String ip, Integer port)
			throws PCPSApplicationException {
		String imsgxml = "";
		MapMchTradDetail mmtd = new MapMchTradDetail();
		mmtd.setMerchantNo(cm.getBranchNo());
		mmtd.setTranDate(cm.getTranDate());
		mmtd.setReqSeqNo(cm.getTranSeqNo());
		MapMchTradDetail serMmtd = mapMchTradDetailDaoImpl
				.getMapMchTradDetailByPk(mmtd);
		List<CardManagerDetail> cmdList = null;
		if (serMmtd != null) {
			return;
		} else {
			// 多卡
			cmdList = tradHistoryDetailDaoImpl.getCardManagerDetailList(cm
					.getCardId());
			imsgxml = getPaidContent(merchantNo, branchNo, cm, cmdList, pwd,
					strS[3].substring(2));
		}
		// if("6101041023".equals(cm.getBranchNo())){
		// System.out.println("========行"+imsgxml);
		// }
		if (!"null".equals(imsgxml) && !PCPSUtil.isEmpty(imsgxml)) {
			String omsgxml = doTran(ip, port, imsgxml);
			Integer respcode = omsgxml.indexOf("<RespCode>00</RespCode>");
			if (respcode > 0) {
				// 已迁移流水
				mapMchTradDetailDaoImpl.insertMapMchTradDetail(mmtd);
			}
		}
	}

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao acDao;

	@EJB(mappedName = "datatranferpibs.impl.TradHistoryDetailDaoImpl")
	private TradHistoryDetailDao tradHistoryDetailDaoImpl;

	private boolean checkList(List<?> list) {
		boolean tag = false;
		if (list != null && list.size() > 0) {
			tag = true;
		}
		return tag;
	}

	private String getPaidContent(String merchantNo, String branchNo,
			CardManager cm, List<CardManagerDetail> cmdList, String pwd,
			String type) throws PCPSApplicationException {
		StringBuilder sb = new StringBuilder();
		sb.append("<?xml version=\"1.0\" encoding=\"gb18030\" ?>");

		sb.append("<TransRequest>");
		sb.append(formatObject("TranCode", MchHisTradDetail.TRANCODE_PAID));
		sb.append(formatObject("MerchantNo", merchantNo));
		sb.append(formatObject("TranTime", PCPSUtil
				.getStringYMDHMSPackedByDate(cm.getTranTime())));
		// <PosNo>00000001</PosNo>
		// <PosSettBatchNo>000001</PosSettBatchNo>
		// <PosSeqNo>031656</PosSeqNo>
		sb.append(formatObject("TranDate", PCPSUtil.getPackedYMDString(cm
				.getTranDate())));
		sb
				.append(formatObject("ReqSeqNo", cm.getBranchNo()
						+ cm.getTranSeqNo()));// 便民驿站无商户请求流水号
		sb.append(formatObject("BrchNo", branchNo));
		sb.append("<ReqBody>");

		sb.append("<Paid>");
		sb.append(formatObject("TotalAmount", cm.getAmount()));
		sb.append(formatObject("CardNum", cm.getCardCount()));
		ActivateCard ac = null;
		// 卡明细
		if (checkList(cmdList)) {
			for (CardManagerDetail card : cmdList) {
				ac = acDao.getActivateCardByCardNo(card.getCardNo());
				if (ac == null) {
					return "null";
				}
				acDao.updateActivateCardPwdByCardNo(card.getCardNo());
				sb.append("<Card>");
				sb.append(formatObject("CardNo", card.getCardNo()));
				sb.append(formatObject("Track2", ac.getTwoTrackContent()));
				sb.append(formatObject("Track3", ac.getThirdTrackContent()));
				sb.append(formatObject("Passwd", pwd));
				sb.append(formatObject("Amount", card.getAmount()));
				sb.append("</Card>");
			}
		}
		sb.append("</Paid>");
		// 会员卡积分或支付,本XML片段可选
		// <MemberShip>
		// <CardNo>会员卡卡号(可选)</CardNo>
		// <Track2>会员卡二磁道信息(可选)</Track2>
		// <Track3>会员卡二磁道信息(可选)</Track3>
		// <!-- (非积分支付时可选或不填) -->
		// <Passwd>会员卡支付密码</Passwd>
		// <!-- (纯预付卡支付时可选或置0) -->
		// <ScorePaidAmount>积分支付发生额(分)</ScorePaidAmount>
		// </MemberShip>

		sb.append(formatObject("OtherPaidAmount", 0));// 现金
		// 交易附加信息,本XML片段可选-->
		sb.append("<Additional>");
		// <Abstract>业务摘要或备注(可选)</Abstract>
		// <!—销售单信息,本XML片段可选-->
		sb.append("<SaleOrder>");
		// <SaleOrderNo>商户销售单号(可选)</SaleOrderNo>
		sb.append(formatObject("BusinessDetailNum", 1));
		sb.append("<BusinessDetail>");
		sb.append(formatObject("BusinessType", type));
		sb.append(formatObject("BusinessAmount", cm.getAmount()));
		sb.append("</BusinessDetail>");

		sb.append("</SaleOrder>");
		sb.append("</Additional>");

		sb.append("</ReqBody>");
		sb.append(formatObject("TranMac", getMac(
				MchHisTradDetail.TRANCODE_PAID, merchantNo, cm.getTranTime(),
				cmdList, pwd)));
		sb.append("</TransRequest>");

		return sb.toString();
	}

	public StringBuilder macBuf = null;

	private String getMac(String tranCode, String merchantNo, Date tranTime,
			List<CardManagerDetail> cardDisList, String pwd) {
		macBuf = new StringBuilder();
		// 本类
		appendMacField(tranCode);
		appendMacField(merchantNo);
		appendMacField(PCPSUtil.getStringYMDHMSPackedByDate(tranTime));
		// 子类
		generateMacField(cardDisList, pwd);
		macBuf.append("00000000");//String trankey = "00000000";
		String macstr = macBuf.toString();
		System.out.println("MAC明文: " + macstr);
		macstr = new SHA1().getDigestOfString(macstr.getBytes());
		return macstr.toString();
	}

	private void appendMacField(String buff) {
		macBuf.append(PCPSUtil.isEmpty(buff) ? "" : buff.trim());
	}

	/**
	 * 产生计算MAC的域
	 */
	private void generateMacField(List<CardManagerDetail> cardDisList,
			String pwd) {
		// 仅处理第1个卡号
		for (CardManagerDetail card : cardDisList) {
			appendMacField(card.getCardNo());
			appendMacField(pwd);
			break;
		}
	}

	public static final byte[] PCPSHDR = "PCPS".getBytes();
	public static final String CHARSET = "GB18030";
	public static final int MSGHDRLEN = 6;
	public static final String TRANKEY = "00000000";

	public static final String XML_NODE_TransResponse = "TransResponse";
	public static final String XML_NODE_RespCode = "RespCode";
	public static final String XML_NODE_RespErrMsg = "RespErrMsg";
	public static final String RESPCODE_SUCC = "00";

	/**
	 * 执行远程调用PCPS 发送交易报文
	 * 
	 * @param imsgxml
	 * @return
	 * @throws PCPSApplicationException
	 */
	private String doTran(String pcpssvr, int pcpsport, String imsgxml)
			throws PCPSApplicationException {
		Socket s = null;
		OutputStream out = null;
		InputStream in = null;
		String omsgxml = null;

		try {
			PCPSUtil.Log("BEGIN CONNECT[" + pcpssvr + ":" + pcpsport + "]...");
			s = getPCPSClient(pcpssvr, pcpsport);
			PCPSUtil.Log("END CONNECT[" + pcpssvr + ":" + pcpsport + "]...");
			out = s.getOutputStream();
			in = s.getInputStream();
			byte[] imsg = imsgxml.getBytes(CHARSET);
			out.write(PCPSHDR, 0, 4);
			out.write(PCPSUtil.formatIntegerLeaderZero(imsg.length, MSGHDRLEN),
					0, 6);
			out.write(imsg);
			out.flush();
			byte[] omsghdr = new byte[MSGHDRLEN];
			int rlen = in.read(omsghdr);
			if (rlen != MSGHDRLEN)
				throw new PCPSApplicationException("", "读报文长度失败!");
			int omsglen = Integer.parseInt(new String(omsghdr, Charset
					.forName(CHARSET)));
			byte[] omsg = new byte[omsglen];
			rlen = in.read(omsg);
			if (rlen != omsglen)
				throw new PCPSApplicationException("", "读报文体失败!");
			omsgxml = new String(omsg, Charset.forName(CHARSET));
		} catch (Exception e) {
			PCPSUtil.Log("与服务器通信失败!", e);
			throw new PCPSApplicationException("", "与服务器通信失败!");
		}

		try {
			if (out != null)
				out.close();
			if (in != null)
				in.close();
			if (s != null)
				s.close();
		} catch (Exception e) {
		}

		return omsgxml;
	}

	/**
	 * 创建SSL SOCKET
	 * 
	 * @return
	 * @throws PCPSApplicationException
	 */
	private static Socket getPCPSClient(String pcpssvr, int pcpsport)
			throws PCPSApplicationException {
		try {
			// Create a trust manager that does not validate certificate chains
			final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
				@Override
				public void checkClientTrusted(final X509Certificate[] chain,
						final String authType) {
				}

				@Override
				public void checkServerTrusted(final X509Certificate[] chain,
						final String authType) {
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			} };

			// Install the all-trusting trust manager
			final SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			// Create an ssl socket factory with our all-trusting manager
			final SSLSocketFactory factory = sc.getSocketFactory();

			// sc.setHostnameVerifier(new NulledHostnameVerifier());
			// sc.setTrustManager(new NulledTrustManager());
			// SSLSocketFactory factory = (SSLSocketFactory)
			// sc.getSocketFactory();
			return factory.createSocket(pcpssvr, pcpsport);
		} catch (Exception e) {
			PCPSUtil.Log("connect to PCPS Server failed!...", e);
			throw new PCPSApplicationException("", "连接到服务器失败!");
		}
	}

	private static String formatObject(String xmllabel, Object obj) {
		StringBuilder sb = new StringBuilder();

		sb.append("<");
		sb.append(xmllabel);
		sb.append(">");

		sb.append(obj.toString().trim());

		sb.append("</");
		sb.append(xmllabel);
		sb.append(">");

		return sb.toString();
	}

	// 老系统卡销售出库
	@EJB(mappedName = "datatranfer.impl.EntityCardDaoImpl")
	private EntityCardDao entityCardDaoImpl;

	@EJB(mappedName = "thirdinterface.impl.MapIssueBranchDaoImpl")
	private MapIssueBranchDao mapIssueBranchDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardStockDaoImpl")
	private CardStockDao cardStockDaoImpl;

	@EJB(mappedName = "thirdinterface.impl.MapSaleBranchDaoImpl")
	private MapSaleBranchDao mapSaleBranchDaoImpl;

	@EJB(mappedName = "thirdinterface.impl.MapCardClassicDaoImpl")
	private MapCardClassicDao mapCardClassicDaoImpl;

	@EJB(mappedName = "datatranfer.impl.ActivateCardBusinessImpl")
	private ActivateCardBusiness activateCardBusinessImpl;

	@EJB(mappedName = "cardmanagement.impl.IssueCardStockDetailDaoImpl")
	private IssueCardStockDetailDao issueCardStockDetailDaoImpl;

	@Override
	public void saleOldCard(String icNo, String startDate, String endDate,
			BigInteger userid, BigInteger faceid)
			throws PCPSApplicationException {
		System.out.println("查询LIST");
		List<Object[]> objs = entityCardDaoImpl.getSaleCardList(startDate,
				endDate);
		System.out.println("集合大小" + objs.size());
		if (objs == null || objs.size() < 1) {
			return;
		}
		Date date = null;
		try {
			date = PCPSUtil.parseYMDDateTime(startDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (Object[] obj : objs) {
			String batchno = obj[0].toString();
			String cardstartseqno = obj[1].toString();
			Integer cardcount = Integer.parseInt(obj[2].toString());
			String frombranchno = obj[3].toString();
			BigInteger customid = new BigInteger(obj[4].toString());
			BigInteger cardparvalue = new BigInteger(obj[5].toString());
			String cardkindid = obj[6].toString();
			String endseqno = obj[7].toString();
			int start = Integer.parseInt(cardstartseqno.substring(6, 12));
			String saleBranchNo = mapSaleBranchDaoImpl
					.getSaleBrchNoFromMapSaleBranch(customid);
			issueCardStockDetailDaoImpl.insertIssueCardStockDetailList(
					mapIssueBranchDaoImpl
							.getIssueBrchNoFromMapIssueBranch(frombranchno),
					icNo + batchno, saleBranchNo, userid, date, faceid,
					cardstartseqno, endseqno, cardcount);
			BigInteger cardClassicId = mapCardClassicDaoImpl
					.getMapCardClassicByBindingTypeNo(cardkindid)
					.getCardClassicId();
			for (int i = start; i < start + cardcount; i++) {
				String cardseqno = batchno + String.format("%06d", i);
				System.out.println("cardseqno===" + cardseqno);
				activateCardBusinessImpl.insertSaleCard(icNo, cardseqno,
						faceid, saleBranchNo, cardparvalue, cardClassicId);
				cardStockDaoImpl.deleteCardStock(cardseqno);
			}
		}
	}
}
